#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<vector>
using namespace std;
string store_path = "E:\\VS_C++\\master";
string init_index_file();
void make_index_file(string index_file, int mode, string add_file, string SHA1_ID, string time);
bool file_have_existed();

int main() //void make_index_file(string add_file, string SHAq_ID, string time);
{
    string index_file;
    index_file = init_index_file();
    make_index_file(index_file, 10064,  "a.txt", "fdsaa96ffss13ce4wq4171c0248420cc03108ef0", "202108012219");
    //以下为测试代码是否正确运行用的
    ifstream f(index_file.c_str(), ios::in | ios::binary);
    int version, file_num;
    f.read((char*)&version, 4);
    f.read((char*)&file_num, 4);
    cout << version << " " << file_num << endl;
    int i;
    char c;
    for(i = 0; i < file_num; i++)
    {
        string a = "";
        int b;
        f.read((char*)&b, 4);
        do{
        f.read((char*)&c, 1);
        a += string(1, c);
        }
        while (c != ' ');
        cout << b << " " << a << endl;         
    }
    system("pause");
}

string init_index_file()
{
    string filename = store_path + "\\.git\\index.bin";
    ifstream f(filename.c_str());
    if(!f)  //index不存在就先执行创建文件，并进行初始化
    {
        ofstream fout(filename.c_str(), ios::out | ios::binary);
        if(!fout) 
        {
            cout <<"创建文件失败" << endl; 
            exit(0);
        }
        int version = 1, file_num = 0;
        fout.write((char*)&version, sizeof(int));
        fout.write((char*)&file_num, sizeof(int));
        fout.close();
    }
    f.close();
    return filename;
}

void make_index_file(string index_file, int mode, string add_file, string SHA1_ID, string time)
{
    fstream f(index_file.c_str(), ios::in | ios::out | ios::binary);
    //暂存区文件数量增加
    int file_num;
    f.seekg(4, ios::beg);
    f.read((char*)&file_num, sizeof(int));
    file_num++;
    f.seekp(4, ios::beg);
    f.write((char*)&file_num, sizeof(int));
    //将添加的文件相关内容写入到index内
    int bit_size = sizeof(int) + add_file.size() + SHA1_ID.size() + time.size() + sizeof(char);  //一个文件存储信息占用的字节
    int offset = 8 + (file_num - 1) * bit_size;  //每次添加的文件在index内的位置
    f.seekp(offset, ios::beg);
    f.write((char*)&mode, sizeof(int));
    char* file_message = (char*)malloc(sizeof(char)*(bit_size-sizeof(int)));
    string message = SHA1_ID + time + add_file + " ";
    strcpy(file_message, message.c_str());
    cout << file_message << endl;
    f.write(file_message, sizeof(char) * (bit_size-sizeof(int)));
    f.close();
}